package com.maltys.tree;

import com.maltys.tree.base.TreeNode;

/**
 * @author Maltyts
 * @link <a href="https://leetcode.cn/problems/path_sum/">...</a>
 */
public class PathSum {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        return preOrderTravel(root, 0, targetSum);
    }

    private boolean preOrderTravel(TreeNode root, int currentSum, int targetSum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            return currentSum + root.val == targetSum;
        }
        boolean leftPath = root.left == null ? false : preOrderTravel(root.left, currentSum + root.val, targetSum);
        boolean rightPath = root.right == null ? false : preOrderTravel(root.right, currentSum + root.val, targetSum);
        return leftPath || rightPath;
    }
}
